package com.himiotech.core.framework.helper.utils;

import com.himiotech.core.project.model.entity.user.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

import java.util.Objects;

/**
 * shiro 工具类
 *
 * @author ruoyi
 * @author wuwenbin
 */
public class ShiroUtils {
    public static Subject getSubject() {
        HimioUtils.checkShiroSecurityManager();
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        getSubject().logout();
    }

    public static User getSysUser() {
        User user = null;
        Object obj = getSubject().getPrincipal();
        if (!Objects.isNull(obj)) {
            user = new User();
            BeanUtils.copyProperties(obj, user);
        }
        return user;
    }

    public static void setSysUser(User user) {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static Long getUserId() {
        return getSysUser().getUserId();
    }

    public static String getUserIdStr() {
        if (getUserId() != null) {
            return getUserId().toString();
        }
        return "";
    }

    public static String getLoginName() {
        if (getSysUser() == null) {
            return "";
        } else {
            return getSysUser().getLoginName();
        }
    }

    public static String getIp() {
        return getSubject().getSession().getHost();
    }

    public static String getSessionId() {
        return String.valueOf(getSubject().getSession().getId());
    }
}
